<template>
  <el-dialog
    v-if="load"
    title="批量图片迁移"
    width="820"
    v-model="visible"
    @close="handleClose"
    draggable
    align-center
  >
    <el-form ref="formRef" label-width="85">
      <el-row :gutter="21">
        <el-col :span="12">
          <el-form-item label="迁移至标签">
            <el-select
              class="w-full"
              v-model="form.transfer_tag"
              placeholder="选择标签"
              filterable
            >
              <el-option
                v-for="item in tagOptions"
                :key="item.custom_tag"
                :label="item.custom_tag"
                :value="item.custom_tag"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="迁移方式">
            <el-select
              class="w-full"
              v-model="form.transfer_method"
              placeholder="迁移方式"
              filterable
            >
              <el-option
                v-for="item in transferMethodOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
            <el-form-item label="迁移至区域">
              <el-radio-group v-model="form.image_region">
                <el-radio
                  v-for="item in imageTypeOptions"
                  :key="item.value"
                  :label="item.value"
                  :disabled="item.disabled"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col> -->
      </el-row>
    </el-form>
    <div class="h-[500px] overflow-y-auto">
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox-group v-model="checkedImage" @change="handleCheckedCitiesChange">
        <el-checkbox
          v-for="(item, index) in records"
          :key="`${item.image_link}-${index}`"
          :label="`${item.image_link}-${index}`"
          :value="`${item.image_link}-${index}`"
          :disabled="item.disabled"
          class="px-1 py-1 mr-1 relative w-[120px]"
        >
          <el-image
            :src="item.image_link_watermark || item.image_link || item.url"
            style="
              width: 100px;
              height: 100px;
              border: 1px solid #f0f0f0;
              border-radius: 4px;
            "
            @contextmenu.prevent
          ></el-image>
          <el-tooltip
            className="item"
            effect="dark"
            :content="item.image_name"
            placement="top"
          >
            <div class="line1 w-[100px] mt-1">{{ item.image_name }}</div>
          </el-tooltip>

          <div class="h-[20px] mt-1">{{ item.image_for_text || "" }}</div>
          <div
            class="absolute left-[28px] top-[1px] flex rounded-tl rounded-br overflow-hidden bg-[#000000]"
          >
            <div
              class="bg-[#3487FF] text-white text-xs px-1 rounded-br"
              v-if="form.image_region == 3 && attr_img == item.image_link"
            >
              主图
            </div>
            <div class="text-white text-xs px-1">
              {{ computeImageType(item.image_link) }}
            </div>
          </div>
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <div class="text-[#ff6334]">
      注：当前操作仅进行图片展示调整，需点击’图片保存‘或‘保存并继续编辑’成功后，调整方才生效
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button type="primary" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { reactive, toRefs } from "vue";
import { transferMethodOptions } from "./data.js";
import { computeImageType } from "@/utils/index.js";
const props = defineProps({
  imageTypeOptions: {
    type: Object,
    default: () => {},
  },
  customTag: {
    type: String,
    default: "",
  },
});

const { customTag } = toRefs(props);

let galleryList = reactive(inject("galleryList"));
let attr_img = reactive(inject("attr_img"));

const tagOptions = computed(() => {
  return galleryList.value
    .filter((i) => !i.delete)
    .map((i) => {
      if (i.custom_tag == customTag.value) {
        i.disabled = true;
      } else {
        i.disabled = false;
      }
      return i;
    });
});

const data = reactive({
  load: false,
  visible: false,
  image_item: {},
  checkAll: false,
  isIndeterminate: false,
  checkedImage: [],
  records: [],
  form: {},
  imageTypeOptions: [],
});

const {
  load,
  visible,
  image_item,
  checkAll,
  isIndeterminate,
  checkedImage,
  records,
  form,
  imageTypeOptions,
} = toRefs(data);

const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  image_item.value = data;
  records.value = image_item.value.values.filter((i) => {
    if (!i.delete) {
      return i;
    }
  });
  form.value.transfer_method = 1;
  form.value.image_region = image_item.value.image_type;
  visible.value = true;
};

const handleCheckAllChange = (val) => {
  checkedImage.value = val
    ? records.value
        .filter((item) => !item.disabled)
        .map((item) => `${item.image_link}-${records.value.indexOf(item)}`)
    : [];
  isIndeterminate.value = false;
};
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length;
  const totalEnabledCount = records.value.filter((item) => !item.disabled).length;
  checkAll.value = checkedCount === totalEnabledCount;
  isIndeterminate.value = checkedCount > 0 && checkedCount < totalEnabledCount;
};

const handleSave = () => {
  if (!checkedImage.value.length) {
    ElMessage.error("至少勾选一项进行修改");
    return;
  }

  if (!form.value.transfer_tag) {
    ElMessage.error("请选择迁移至标签");
    return;
  }

  galleryList.value.forEach((gallery) => {
    if (gallery.custom_tag === form.value.transfer_tag) {
      const targetContents = gallery.contents.find(
        (content) => content.image_type === form.value.image_region
      );

      if (targetContents) {
        image_item.value.values.forEach((image) => {
          const uniqueIdentifier = `${image.image_link}-${records.value.indexOf(image)}`;
          if (checkedImage.value.includes(uniqueIdentifier)) {
            const newObj = { ...image };
            delete newObj.id;
            if (attr_img.value == image.image_link) {
              targetContents.values.unshift(newObj);
            } else {
              targetContents.values.push(newObj);
            }
            if (form.value.transfer_method == 1) {
              if (image.id) {
                image.delete = 1;
              } else {
                image_item.value.values = image_item.value.values.filter(
                  (img) =>
                    (img.id || `${img.image_link}-${records.value.indexOf(img)}`) !==
                    uniqueIdentifier
                );
              }
            }
          }
        });
      }
    }
    return gallery;
  });
  handleClose();
};

const handleClose = () => {
  records.value = [];
  image_item.value = {};
  checkedImage.value = [];
  checkAll.value = false;
  isIndeterminate.value = false;
  visible.value = false;
  form.value.transfer_tag = "";
};

defineExpose({ open });
</script>
<style lang="scss" scoped>
.el-checkbox-group {
  :deep(.el-checkbox) {
    height: 140px;
    margin-bottom: 12px;
  }
}
</style>
